package com.ruowei.modules.foodOrder.web.rest;

import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruowei.common.error.exception.BadRequestAlertException;
import com.ruowei.common.lang.StringUtils;
import com.ruowei.common.querydsl.OptionalBooleanBuilder;
import com.ruowei.config.ApplicationProperties;
import com.ruowei.modules.foodOrder.domain.QQrAddress;
import com.ruowei.modules.foodOrder.domain.QrAddress;
import com.ruowei.modules.foodOrder.repository.QrAddressRepository;

import com.ruowei.modules.foodOrder.web.dto.AddressListDTO;
import com.ruowei.modules.foodOrder.web.dto.AlterAddressDTO;
import com.ruowei.modules.foodOrder.web.dto.QrAddressDTO;
import com.ruowei.modules.foodOrder.web.dto.QrCodeDTO;
import com.ruowei.modules.sys.utils.CommonUtils;
import com.ruowei.modules.yueche.util.QRcodeUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing {@link QrAddress}.
 */
@RestController
@RequestMapping("/api")
@Transactional
@Api(tags = "地址管理")
public class QrAddressResource {

    private final Logger log = LoggerFactory.getLogger(QrAddressResource.class);

    private final QrAddressRepository qrAddressRepository;
    private final JPAQueryFactory queryFactory;
    private final QQrAddress QQA = QQrAddress.qrAddress;
    private final ApplicationProperties applicationProperties;

    public QrAddressResource(QrAddressRepository qrAddressRepository, JPAQueryFactory queryFactory, ApplicationProperties applicationProperties) {
        this.qrAddressRepository = qrAddressRepository;
        this.queryFactory = queryFactory;
        this.applicationProperties = applicationProperties;
    }

    @GetMapping("/applet/qr-addresses")
    @ApiOperation(value = "下拉列表：地址-小程序")
    public ResponseEntity<List<AddressListDTO>> getAllQrAddresses() {
        List<AddressListDTO> dtoList = new ArrayList<>();
        qrAddressRepository.findAllByStatus(true)
            .forEach(qrAddress -> {
                AddressListDTO dto = new AddressListDTO();
                dto.setId(qrAddress.getId());
                dto.setDetailAddress(qrAddress.getDetailAddress());
                dtoList.add(dto);
            });
        return ResponseEntity.ok(dtoList);
    }

    @PostMapping("/qr-addresses")
    @ApiOperation(value = "新增地址-web")
    public ResponseEntity<Void> getQrAddress(@RequestBody QrAddressDTO dto) {
        if (dto == null) {
            throw new BadRequestAlertException("请填写地址信息");
        }
        qrAddressRepository.findByDetailAddressAndStatus(dto.getDetailAddress(), true)
            .ifPresent(address -> {
                if (dto.getDetailAddress().equals(address.getDetailAddress())) {
                    throw new BadRequestAlertException("地址已存在");
                }
            });
        QrAddress qrAddress = new QrAddress();
        qrAddress.setAddressCode(CommonUtils.getUUID());
        qrAddress.setDetailAddress(dto.getDetailAddress());
        qrAddress.setQrUrl(dto.getQrUrl());
        qrAddress.setStatus(true);
        qrAddressRepository.save(qrAddress);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/qr-addresses")
    @ApiOperation(value = "修改地址-web")
    public ResponseEntity<Void> alterAddress(AlterAddressDTO dto) {
        if (dto.getId() == null) {
            throw new BadRequestAlertException("ID不能为空");
        }
        Optional<QrAddress> qrAddress = qrAddressRepository.findById(dto.getId());
        if (!qrAddress.isPresent()) {
            throw new BadRequestAlertException("地址信息不存在");
        }
        Boolean exists = qrAddressRepository.existsByDetailAddressAndStatusAndIdNot(dto.getDetailAddress(),true, dto.getId());
        if (exists) {
            throw new BadRequestAlertException("地址已存在");
        }
        QrAddress address = qrAddress.get();
        address.setDetailAddress(dto.getDetailAddress());
        address.setQrUrl(dto.getQrUrl());
        return ResponseEntity.ok().build();
    }

    @GetMapping("/qr-addresses/list")
    @ApiOperation(value = "获取地址列表-web")
    public ResponseEntity<List<QrAddress>> getQrAddress(@RequestParam(required = false) String detailAddress,
                                                        Pageable pageable) {
        OptionalBooleanBuilder predicate = new OptionalBooleanBuilder()
            .notEmptyAnd(QQA.detailAddress::contains, detailAddress);
        JPAQuery<QrAddress> jpaQuery = queryFactory.select(Projections.bean(QrAddress.class, QQA.id, QQA.addressCode,
            QQA.detailAddress, QQA.qrUrl, QQA.status))
            .from(QQA)
            .where(QQA.status.eq(true).and(predicate.build()))
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize());
        Page<QrAddress> page = new PageImpl<>(jpaQuery.fetch(), pageable, jpaQuery.fetchCount());
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    @PutMapping("/qr-addresses/{id}")
    @ApiOperation(value = "删除地址-web")
    public ResponseEntity<Void> deleteAddress(@PathVariable Long id) {
        if (id == null) {
            throw new BadRequestAlertException("ID不能为空");
        }
        qrAddressRepository.findById(id)
            .ifPresent(qrAddress -> {
                qrAddress.setStatus(false);
                qrAddressRepository.saveAndFlush(qrAddress);
            });
        return ResponseEntity.ok().build();
    }

    @PostMapping("/qr-addresses/qrCode")
    @ApiOperation(value = "批量生成二维码-web")
    public ResponseEntity<List<QrCodeDTO>> getQrCodes(@RequestBody List<Long> ids) {
        if (ids == null) {
            throw new BadRequestAlertException("ID不能为空");
        }
        List<QrCodeDTO> urls = new ArrayList<>();
        ids.forEach(id -> {
            qrAddressRepository.findById(id)
                .ifPresent(qrAddress -> {
                    try {
                        QrCodeDTO dto = new QrCodeDTO();
                        String url = QRcodeUtil.QREncodeTool(qrAddress.getDetailAddress(), qrAddress.getDetailAddress() + ".png");
                        qrAddress.setQrUrl(url);
                        qrAddressRepository.save(qrAddress);
                        dto.setQrUrl(url);
                        dto.setPictureName(qrAddress.getDetailAddress() + ".png");
                        urls.add(dto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
        });
        return ResponseEntity.ok(urls);
    }

}
